package com.easy.work.function.mall.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.base.syslib.Logs;
import com.base.syslib.pulltorefresh.PullToRefreshBase;
import com.base.syslib.pulltorefresh.PullToRefreshListView;
import com.base.syslib.util.DensityUtil;
import com.base.syslib.util.MessageTools;
import com.easy.work.R;
import com.easy.work.app.AppSession;
import com.easy.work.app.BaseActivity;
import com.easy.work.function.mall.adapter.SelectAddressAdapter;
import com.easy.work.function.mall.bean.AddressBean;
import com.easy.work.function.mall.bean.DeleteEvent;
import com.easy.work.function.mall.bean.SelectAddressEvent;
import com.easy.work.http.BaseResponse;
import com.easy.work.http.HttpClient;
import com.easy.work.http.request.AllAddressRequest;
import com.easy.work.http.request.DeleteAddressRequest;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.easy.work.R.id.listView;

/**
 * @author zhangfeng
 * @date 2017/12/24
 * @desc 选择地址
 */

public class SelectAddressActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ListView> {

    private static final String TAG = SelectAddressActivity.class.getSimpleName();

    @BindView(listView)
    PullToRefreshListView refreshListView;

    private SelectAddressAdapter mAdapter;

    public static void start(Context ctx) {
        Intent intent = new Intent(ctx, SelectAddressActivity.class);
        ctx.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_address);
        ButterKnife.bind(this);
        initTitle("选择地址");
        initListView();
    }

    /**
     * ListView初始化
     */
    private void initListView() {
        refreshListView.setPullLoadEnabled(false);
        refreshListView.setPullRefreshEnabled(true);
        refreshListView.setOnRefreshListener(this);

        ListView listView = refreshListView.getRefreshableView();
        listView.setDivider(new ColorDrawable(0xffF5F5F5));
        listView.setDividerHeight(DensityUtil.dip2px(this, 8));

        List<AddressBean.ListEntity> list = new ArrayList<>();
        mAdapter = new SelectAddressAdapter(this, 1, list);
        listView.setAdapter(mAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                AddressBean.ListEntity bean = (AddressBean.ListEntity) adapterView.getAdapter().getItem(position);
                EventBus.getDefault().post(new SelectAddressEvent(bean));
                finish();
            }
        });
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        getAllAddressList();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        refreshListView.onPullUpRefreshComplete();
        refreshListView.onPullDownRefreshComplete();
    }

    /**
     * 获取所有收货地址
     */
    private void getAllAddressList() {
        final AllAddressRequest request = new AllAddressRequest();
        request.userId = AppSession.getInstance().getUserId();
        Logs.e(TAG, "userId:" + request.userId);
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                refreshListView.onPullUpRefreshComplete();
                refreshListView.onPullDownRefreshComplete();
                handleData(response);
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                refreshListView.onPullUpRefreshComplete();
                refreshListView.onPullDownRefreshComplete();
                MessageTools.showToast(getApplicationContext(), msg);
            }
        });
    }

    /**
     * 数据处理
     */
    private void handleData(BaseResponse response) {
        AddressBean bean = (AddressBean) response;
        if (bean != null && bean.list != null && !bean.list.isEmpty()) {
            mAdapter.refreshData(bean.list);
        } else {
            mAdapter.clearData();
            MessageTools.showToast(getApplicationContext(), "暂无数据");
        }
    }

    @OnClick(R.id.btn_new_address)
    void addNewAddress() {
        EditAddressActivity.start(SelectAddressActivity.this, null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        AppSession.setPullFormartRefreshTime(refreshListView);
        refreshListView.doPullRefreshing(true, 0);
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeleteEvent(DeleteEvent event) {
        showDialog();
        final DeleteAddressRequest request = new DeleteAddressRequest();
        request.consigneeId = event.consigneeId;
        Logs.e(TAG, "consigneeId:" + event.consigneeId);
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                closeDialog();
                AppSession.setPullFormartRefreshTime(refreshListView);
                refreshListView.doPullRefreshing(true, 0);
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                closeDialog();
                MessageTools.showToast(getApplicationContext(), msg);
            }
        });
    }
}
